package com.dld.coupon.util;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.widget.TextView;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MKEvent;
import com.baidu.mapapi.MKGeneralListener;
import com.dld.android.persistent.SharePersistent;
import com.dld.android.util.LogUtils;
import com.dld.coupon.activity.ActivityManager;
import com.dld.coupon.activity.CityActivity;
import com.dld.coupon.activity.R;
import com.dld.coupon.db.GenericDAO;
import com.dld.coupon.view.DialogHelper;
import com.tencent.weibo.utils.Cache;

public class MapUtil {
	private static final String KEY = "4EE0F29E7EB1FC29EAC2B755CE57511E9535CF98";
	private static String address;
	public static boolean cityCanceled = false;
	private static String cityId;
	private static String cityName;
	public static String cityOfRange = new String();
	static AlertDialog d;
	public static LatAndLon location;
	private static LocationListener locationListener;
	public static BMapManager manager;
	public static String range;

	private static String previous_city;

	public static void destory() {
		if (manager != null) {
			manager.destroy();
			manager = null;
		}
	}

	public static String getCity() {
		String str = SharePersistent.get("city_name");
		if (StringUtils.isEmpty(str))
			str = "北京";
		return str;
	}

	public static String getCityId() {
		String str = SharePersistent.get("city_id");
		if (StringUtils.isEmpty(str))
			str = "101120103";
		return str;
	}

	public static String getGpsCity() {
		String str;
		if (StringUtils.isEmpty(cityName)) {
			cityName = SharePersistent.get("gps_city");
			if (StringUtils.isEmpty(cityName))
				str = getCity();
			else
				str = cityName;
		} else {
			str = cityName;
		}
		return str;
	}

	public static String getGpsCityId() {
		String str;
		if (StringUtils.isEmpty(cityId)) {
			cityId = SharePersistent.get("gps_city_id");
			if (StringUtils.isEmpty(cityId))
				str = getCityId();
			else
				str = cityId;
		} else {
			str = cityId;
		}
		return str;
	}

	public static boolean isInited() {
		boolean i;
		if (location == null)
			i = false;
		else
			i = true;
		return i;
	}

	public static void openMap(double paramDouble1, double paramDouble2,
			String paramString) {
		if ((paramDouble1 <= 0.0D) || (paramDouble2 <= 0.0D))
			return;
		try {
			DialogHelper.showInvalidLatLon();
			Object localObject = paramString.replace("(", "（")
					.replace(")", "）").replace("\"", " ");
			localObject = "(\"" + Uri.encode((String) localObject, "utf-8")
					+ "\")";
			localObject = new Intent("android.intent.action.VIEW", Uri
					.parse(new StringBuilder("geo:").append(paramDouble1)
							.append(",").append(paramDouble2).append("?q=")
							.append(paramDouble1).append(",").append(
									paramDouble2).toString()
							+ (String) localObject));
			((Intent) localObject).setFlags(0);
			((Intent) localObject).setClassName("com.google.android.apps.maps",
					"com.google.android.maps.MapsActivity");
			ActivityManager.getCurrent().startActivity((Intent) localObject);
		} catch (Exception localException) {
			LogUtils.e("test", "", localException);
		}
		double d1 = paramDouble1;
		paramDouble1 = paramDouble2;
		paramDouble2 = d1;

	}

	public static void regist(final LocationObserver observer,
			final Handler paramHandler, final Activity activity) {

		HandlerThread ht = new HandlerThread("");
		ht.start();
		final Handler handler = new Handler(ht.getLooper());
		handler.post(new Runnable() {

			public void run() {
				try {

					if (MapUtil.manager == null) {
						MapUtil.manager = new BMapManager(ActivityManager
								.getCurrent());
					}
					LocationListener location_listener = new LocationListener() {
						public void onLocationChanged(Location paramLocation) {

							Log.v("", "**************   onlocation changed   "
									+ paramLocation);
							if (paramLocation == null)
								return;
							try {
								if (MapUtil.location == null) {
									MapUtil.location = new MapUtil.LatAndLon();
								}
								MapUtil.location.lat = paramLocation
										.getLatitude();
								MapUtil.location.lon = paramLocation
										.getLongitude();
								observer.onLocationChanged(MapUtil.location);
								MapUtil.reverseGeoCode(paramHandler, activity,
										observer);

							} catch (Exception localException) {
								observer.onFailed();
								LogUtils.e("test", localException);
							}
						}
					};

					MapUtil.manager.init(KEY, new MyGeneralListener());
					MapUtil.manager.start();
					MapUtil.manager.getLocationManager()
							.requestLocationUpdates(location_listener);

				} catch (Exception e) {
					LogUtils.e("test", e);
				}
			}
		});

	}

	public static void destoryMap() {
		if (manager != null) {
			manager.destroy();
		}
	}

	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
	static class MyGeneralListener implements MKGeneralListener {

		public void onGetNetworkState(int iError) {
			Log.v("", "onGetNetworkState  ****     " + iError);
		}

		public void onGetPermissionState(int iError) {
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				Log.v("", "onGetPermissionState  ****     " + iError);
			}
		}

	}

	public static void reverseGeoCode(Handler paramHandler,
			Activity paramActivity, LocationObserver ob) {
		try {

			URL url = new URL("http://ditu.google.cn/maps/geo?output=json&q="
					+ location.lat + "," + location.lon);
			URLConnection httpcnn = url.openConnection();
			httpcnn.setConnectTimeout(1000 * 15);
			InputStream input = url.openStream();

			StringBuilder sb = new StringBuilder();
			char[] buff = new char[1024];
			int len = 0;
			InputStreamReader inreader = new InputStreamReader(input);
			while ((len = inreader.read(buff)) > 0) {
				sb.append(buff, 0, len);
			}
			input.close();

			JSONObject jobj = new JSONObject(sb.toString());
			JSONArray jarray = (JSONArray) jobj.get("Placemark");
			JSONObject jaddress = jarray.getJSONObject(0);

			if (!StringUtils.isEmpty(sb.toString())) {

				address = jaddress.getString("address");
				JSONObject addressdetail = jaddress
						.getJSONObject("AddressDetails");
				JSONObject countroy = addressdetail.getJSONObject("Country");
				JSONObject admin = countroy.getJSONObject("AdministrativeArea");
				JSONObject locality = admin.getJSONObject("Locality");
				cityName = locality.getString("LocalityName");
				Log.v("", "******** reverse code   "+cityName);
				cityId = GenericDAO.getInstance(ActivityManager.getCurrent())
						.getCityIdByName( cityName);

				Log.v("", "********************** gps  change  city id  "
						+ cityId);
				updateAddress(paramActivity, paramHandler);
				Cache.put("gps_address", sb.toString());
				Cache.put("gps_city", cityName);
				Cache.put("gps_city_id", cityId);
				SharePersistent.set("gps_city", cityName);
				SharePersistent.set("gps_city_id", cityId);

				if (cityName != null && (!cityName.equals(previous_city))) {
					ob.onCityChanged(cityName);
				} else {
					ob.onCityChanged(null);
				}
				SharePersistent.set("city_name", cityName);
				SharePersistent.set("city_id", cityId);

			}
		} catch (Exception localException) {
			LogUtils.e("test", "", localException);
		}
	}

	public static void showCityChanged(final String paramString) {
		if (d == null) {
			d = new AlertDialog.Builder(ActivityManager.getCurrent()).setTitle(
					"切换城市").setMessage("GPS定位您当前在" + paramString + "，需要切换吗？")
					.setPositiveButton("切换",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface paramDialogInterface,
										int paramInt) {
									Log.v("",
											"****************city  changed     "
													+ MapUtil.cityId + ","
													+ MapUtil.cityName);
									MapUtil.cityId = GenericDAO.getInstance()
											.getCityIdByName(paramString);
									MapUtil.cityName = paramString;
									if (MapUtil.cityId != null) {
										SharePersistent.set("city_id",
												MapUtil.cityId);
										SharePersistent.set("city_name",
												MapUtil.cityName);
										CityActivity.notifyChange(
												MapUtil.cityName,
												MapUtil.cityId);
										MapUtil.d = null;
									}
								}
							}).setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(
										DialogInterface paramDialogInterface,
										int paramInt) {
									MapUtil.cityCanceled = true;
									MapUtil.d = null;
								}
							}).create();
			d.setCanceledOnTouchOutside(true);
			d.show();
		}
	}

	public static void unregist() {
		if (locationListener != null) {
			manager.getLocationManager().removeUpdates(locationListener);
			manager = null;
		}
	}

	public static void updateAddress(Activity paramActivity,
			Handler paramHandler) {
		updateAddress(paramActivity, paramHandler, 0);
	}

	private static void updateAddress(final Activity paramActivity,
			final Handler paramHandler, final int paramInt) {
		try {
			final TextView localTextView = (TextView) paramActivity
					.findViewById(R.id.location);
			if (localTextView == null) {
				if (paramInt < 2)
					new Timer().schedule(new TimerTask() {
						public void run() {
							MapUtil.updateAddress(paramActivity, paramHandler,
									paramInt);
						}
					}, 3000L);
			} else {
				paramHandler.post(new Runnable() {
					public void run() {

						if (!StringUtils.isEmpty(MapUtil.address))
							MapUtil.range = "我的位置：" + MapUtil.address;
						else
							MapUtil.range = "十分抱歉，未能确定您所在的位置。";
						localTextView.setText(MapUtil.range);
					}

				});

			}
		} catch (Exception localException) {
			LogUtils.e("test", "", localException);
		}
	}

	public static class LatAndLon {
		public double lat;
		public double lon;

		public double getLatitude() {
			return this.lat;
		}

		public double getLongitude() {
			return this.lon;
		}
	}

	public static abstract interface LocationObserver {
		public abstract void onFailed();

		public abstract void onLocationChanged(MapUtil.LatAndLon paramLatAndLon);

		public abstract void onCityChanged(String currentCity);
	}

}
